//V0.01 win10系统下permission和workspacetype初始化中文乱码
package org.mindrive.system.init;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.mindrive.system.collection.system.*;
import org.mindrive.system.parameter.schedule.ScheduleParameter;
import org.mindrive.system.service.BaseService;
import org.mindrive.system.service.schedule.ScheduleService;
import org.mindrive.system.service.system.DictionaryService;
import org.mindrive.system.service.system.PermissionTemplateReaderHandler;
import org.mindrive.system.service.system.QuartzJobService;
import org.mindrive.system.service.upgrade.UpgradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.Resource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class InitController extends BaseService implements ApplicationRunner {

    @Value("classpath:data/permissions.xlsx")
    private Resource permissionsFile;

    @Autowired
    private PermissionTemplateReaderHandler permissionTemplateReaderHandler;

    @Autowired
    private QuartzJobService quartzJobService;
    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private UpgradeService upgradeService;

    @Autowired
    private DictionaryService dictionaryService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        initRoles();
        initPermissions();
        initFolder();
//        dictionaryService.init();
        initUser();
        initQuartzJob();
        startQuartzJob();
        startSchedule();
        upgradeService.upgrade();
        log.debug("程序启动成功");
    }


    private void initRoles() {
        log.info("初期化角色开始");
        try {
            int count = roleDao.getCountByCode(ROLE_CODE_SYSTEM_ADMIN);
            if (count == 0) {
                RoleEntity roleEntity = new RoleEntity();
                roleEntity.setCode(ROLE_CODE_SYSTEM_ADMIN);
                roleEntity.setName("系统管理员");
                roleEntity.setWorkspaceId("");
                roleEntity.setCreatedAt(new Date());
                roleEntity.setCreator("default");
                roleDao.save(roleEntity);
            }
            count = roleDao.getCountByCode(ROLE_CODE_SYSTEM_USER);
            if (count == 0) {
                RoleEntity roleEntity = new RoleEntity();
                roleEntity.setCode(ROLE_CODE_SYSTEM_USER);
                roleEntity.setName("普通用户");
                roleEntity.setWorkspaceId("");
                roleEntity.setCreatedAt(new Date());
                roleEntity.setCreator("default");
                roleDao.save(roleEntity);
            }
        } catch (Exception ex) {
            log.error("初期化角色失败。", ex);
        }
        log.info("初期化角色结束");
    }

    private void initPermissions() {
        log.info("初期化权限开始");
        try {
            int count = permissionDao.count();
            if (count == 0) {
                // 删除角色的所有权限
                rolePermissionDao.remove(new QueryWrapper<RolePermissionEntity>());
                permissionPathDao.remove(new QueryWrapper<PermissionPathEntity>());
                InputStream inputstream = permissionsFile.getInputStream();
                EasyExcel.read(inputstream, permissionTemplateReaderHandler).doReadAll();
            }

        } catch (Exception ex) {
            log.error("初期化权限失败。", ex);
        }
        log.info("初期化权限结束");
    }

    private void initFolder() {
        File appFilesFolder = new File(destPath + File.separator + APP_FILES);
        if (!appFilesFolder.exists()) {
            appFilesFolder.mkdir();
        }
        File avatarFolder = new File(destPath + File.separator + AVATAR);
        if (!avatarFolder.exists()) {
            avatarFolder.mkdir();
        }
    }

    private void initUser() {
        QueryWrapper<UserEntity> query = new QueryWrapper<UserEntity>();
        query.eq("user_id", USER_ID_SYSTEM);
        UserEntity admin = userDao.getOne(query, false);
        if (admin == null) {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String pwd = encoder.encode(USER_ID_SYSTEM + PASSWORD_INIT);
            admin = new UserEntity();
            admin.setUserId(USER_ID_SYSTEM);
            admin.setUserName("管理员");
            admin.setPassword(pwd);
            admin.setStatus(USER_STATUS_NORMAL);
            admin.setFillOutStatus(YES_STATUS);
            userDao.save(admin);
            addUserRole(admin, ROLE_CODE_SYSTEM_ADMIN);
        } else {
            addUserRole(admin, ROLE_CODE_SYSTEM_ADMIN);
        }

    }

    private void addUserRole(UserEntity user, String roleCode) {
        RoleEntity role = roleDao.getRoleByCode("", roleCode);

        QueryWrapper<UserRoleEntity> query = new QueryWrapper<UserRoleEntity>();
        query.eq("role_id", role.getId()).eq("user_id", user.getId());
        int count = userRoleDao.count(query);
        if (count == 0) {
            UserRoleEntity relation = new UserRoleEntity();
            relation.setRoleId(role.getId());
            relation.setUserId(user.getId());
            relation.setWorkspaceId("");
            userRoleDao.save(relation);
            log.debug("添加用户角色成功。userId:[{}],role_id:[{}]", user.getId(), role.getId());
        }

    }

    /**
     * 定时任务初期化
     */
    private void initQuartzJob() {
        log.info("初期化定时任务开始。");


        log.info("初期化定时任务结束。");
    }

    private void startQuartzJob() {

        QueryWrapper<QuartzJobEntity> query = new QueryWrapper<QuartzJobEntity>();
        query.eq("status", QUARTZ_JOB_STATUS_NORMAL);
        List<QuartzJobEntity> jobs = quartzJobDao.list(query);
        for (QuartzJobEntity entity : jobs) {
            try {
                this.quartzJobService.schedulerAdd(entity);
            } catch (Exception ex) {
                log.error("定时任务启动失败。id:[{}]", entity.getId(), ex);
            }
        }

    }

    /**
     * 初始化日程管理
     * @Author mwh
     * @Date 15:18 2023/12/28
     **/
    private void startSchedule(){
        log.info("初始化日程管理 开始。");
        //查询当前日程表是否有数据
        final int count = scheduleDao.count();
        if (count==0){
            //若没有数据,则自动生成本周日程数据
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
//            System.out.println("本周周一的日期为：" + year + "-" + month + "-" + day);

            SimpleDateFormat sdfByName = new SimpleDateFormat("yyyy年MM月");
            int weekOfMonth = calendar.get(Calendar.WEEK_OF_MONTH);
            ScheduleParameter importParameter = new ScheduleParameter();
            importParameter.setScheName(sdfByName.format(new Date())+"第"+weekOfMonth+"周主要领导日程");
            importParameter.setBeginTime(year + "-" + month + "-" + day);
            importParameter.setType(0);
            scheduleService.initCreate(importParameter);

            ScheduleParameter normalParameter = new ScheduleParameter();
            normalParameter.setScheName(sdfByName.format(new Date())+"第"+weekOfMonth+"周其他领导日程");
            normalParameter.setBeginTime(year + "-" + month + "-" + day);
            normalParameter.setType(1);
            scheduleService.initCreate(normalParameter);
        }
        log.info("初始化日程管理 结束。");
    }
}
